package com.hrm.action;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import com.hrm.config.JSPPage;
import com.hrm.config.MsgType;
import com.hrm.entity.Message;
import com.hrm.entity.Role;
import com.hrm.entity.User;
import com.hrm.entity.UserRole;
import com.hrm.service.RoleService;
import com.hrm.service.UserLogService;
import com.hrm.service.UserService;
import com.hrm.util.DateUtil;
import com.hrm.util.JSONUtil;
import com.hrm.util.Page;
import com.hrm.util.TreeNode;


@Controller
@RequestMapping("/role.do")
public class RoleAction {
	private static final Log log = LogFactory.getLog(RoleAction.class); 
	@Autowired
	private RoleService roleService;
	@Autowired
	private UserService userService;
	@Autowired
	private UserLogService userLogService;
	public UserLogService getUserLogService() {
		return userLogService;
	}
	public void setUserLogService(UserLogService userLogService) {
		this.userLogService = userLogService;
	}
	public UserService getUserService() {
		return userService;
	}
	public void setUserService(UserService userService) {
		this.userService = userService;
	}
	public RoleService getRoleService() {
		return roleService;
	}
	public void setRoleService(RoleService roleService) {
		this.roleService = roleService;
	}
	@RequestMapping(params = "method=getRoles")
	public String getRoles(HttpServletRequest request,
			HttpServletResponse response, ModelMap map){
		String result= JSONUtil.parseList(roleService.getRoles());
		try {
			response.getWriter().print(result);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
		
	}
	@RequestMapping(params = "method=getRoleTree")
	public String getRoleTree(HttpServletRequest request,
			HttpServletResponse response, ModelMap map){
		List<Role> roles = roleService.getRoles();
		TreeNode treeNode = new TreeNode();
		treeNode.setData("角色列表");
		treeNode.setState("open");
		List<TreeNode> tList = new ArrayList<TreeNode>();
		long userId = Long.parseLong(request.getParameter("userId")==null?"-1":request.getParameter("userId"));
		List<Integer> userRoleIds=new ArrayList<Integer>();
		if(userId!=-1){//需要查询出该用户所属的角色列表
			List<UserRole> tmp = roleService.getRolesByUserId(userId);
			if(tmp!=null){
				for(UserRole ur:tmp){
					userRoleIds.add(ur.getRoleId());
				}
			}
		}
		treeNode.setCheckboxs(userRoleIds);
		for(int i=0;i<roles.size();i++){
			TreeNode tmpNode = new TreeNode();
			tmpNode.setData(roles.get(i).getRoleName());
			Map<String, Object> attr = new HashMap<String, Object>();
			int id=roles.get(i).getId();
			attr.put("id", id);
			if(userRoleIds.contains(id)){
				attr.put("class", "js-tree-checked");
			}
			tmpNode.setAttr(attr);
			tList.add(tmpNode);
		}
		treeNode.setChildren(tList);
		String result= treeNode.toJSONString();
		try {
			response.getWriter().print(result);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
		
	}
	@RequestMapping(params = "method=getRoleById")
	public String getRoleById(HttpServletRequest request,
			HttpServletResponse response, ModelMap map){
		long id = Long.parseLong(request.getParameter("id"));
		Role role = roleService.getRoleById(id);
		if(role==null){
			Message message = new Message();
			message.setMsg("获取角色信息失败!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		String result= role.toJSONString();
		try {
			response.getWriter().print(result);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
		
	}
	
	@RequestMapping(params = "method=updateRole")
	public String updateRole(HttpServletRequest request,
			HttpServletResponse response, ModelMap map){
		long id = Long.parseLong(request.getParameter("id"));
		Role role = roleService.getRoleById(id);
		if(role==null){
			Message message = new Message();
			message.setMsg("获取角色信息失败!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		map.put("role", role);
		return JSPPage.ROLE_EDIT;
	}
	@RequestMapping(params = "method=getUsersByRoleId")
	public String getUsersByRoleId(HttpServletRequest request,
			HttpServletResponse response, ModelMap map){
		long id = Long.parseLong(request.getParameter("id"));
		log.error(id);
		Page page=new Page();
		page.setPagesize(Integer.parseInt(request.getParameter("rows")));
		page.setCurrentpage(Integer.parseInt(request.getParameter("page")));
		page.setCounts(roleService.getUsersCountsByRoleId(id));
		List<User> users = roleService.getUsersByRoleId(page, id);
		if(users==null){
			Message message = new Message();
			message.setMsg("该角色下无用户!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}else{
			try {
				Map<String, Object> resultMap = new HashMap<String, Object>();
				resultMap.put("page", page.getCurrentpage()+"");
				resultMap.put("total", page.getCountPage()+"");
				resultMap.put("records", page.getCounts()+"");
				List<Map<String, Object>> rows = new ArrayList<Map<String, Object>>();
				for(User u:users){
					Map<String, Object> rowMap =new HashMap<String, Object>();
					rowMap.put("id", u.getId());
					List<String> list = new ArrayList<String>();
					list.add(u.getId()+"");
					list.add(u.getUserName()+"");
					//list.add(u.getPassword()+"");
					list.add(u.getRId()+"");
					list.add(u.getCreateUserName()+"");
					list.add(DateUtil.formate(u.getCreateDate())+"");
					List<Role> roles=new ArrayList<Role>();
					roles=userService.getRolesByUserId(u.getId());
					StringBuffer stringBuffer = new StringBuffer();
					for(int i=0;i<roles.size();i++){
						if(i!=roles.size()-1){
							stringBuffer.append(roles.get(i).getRoleName()+",");
						}else{
							stringBuffer.append(roles.get(i).getRoleName());
						}
					}
					list.add(stringBuffer.toString());
					rowMap.put("cell", list);
					rows.add(rowMap);
				}
				resultMap.put("rows", rows);
				response.getWriter().print(JSONUtil.parseMap(resultMap));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
	@RequestMapping(params = "method=getUsersNotRoleId")
	public String getUsersNotRoleId(HttpServletRequest request,
			HttpServletResponse response, ModelMap map){
		long id = Long.parseLong(request.getParameter("id"));
		Page page=new Page();
		page.setPagesize(Integer.parseInt(request.getParameter("rows")));
		page.setCurrentpage(Integer.parseInt(request.getParameter("page")));
		page.setCounts(roleService.getUsersCountsNotRoleId(id));
		List<User> users = roleService.getUsersNotRoleId(page, id);
		if(users==null){
			Message message = new Message();
			message.setMsg("所有用户均为该角色!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}else{
			try {
				Map<String, Object> resultMap = new HashMap<String, Object>();
				resultMap.put("page", page.getCurrentpage()+"");
				resultMap.put("total", page.getCountPage()+"");
				resultMap.put("records", page.getCounts()+"");
				List<Map<String, Object>> rows = new ArrayList<Map<String, Object>>();
				for(User u:users){
					Map<String, Object> rowMap =new HashMap<String, Object>();
					rowMap.put("id", u.getId());
					List<String> list = new ArrayList<String>();
					list.add(u.getId()+"");
					list.add(u.getUserName()+"");
					//list.add(u.getPassword()+"");
					list.add(u.getRId()+"");
					list.add(u.getCreateUserName()+"");
					list.add(DateUtil.formate(u.getCreateDate())+"");
//					List<Role> roles=new ArrayList<Role>();
//					roles=userService.getRolesByUserId(u.getId());
//					StringBuffer stringBuffer = new StringBuffer();
//					for(int i=0;i<roles.size();i++){
//						if(i!=roles.size()-1){
//							stringBuffer.append(roles.get(i).getRoleName()+",");
//						}else{
//							stringBuffer.append(roles.get(i).getRoleName());
//						}
//					}
//					list.add(stringBuffer.toString());
					rowMap.put("cell", list);
					rows.add(rowMap);
				}
				resultMap.put("rows", rows);
				response.getWriter().print(JSONUtil.parseMap(resultMap));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
	@RequestMapping(params = "method=updateRoleById")
	public String updateRoleById(HttpServletRequest request,
			HttpServletResponse response, ModelMap map){
		long id = Long.parseLong(request.getParameter("id")==null?"-1":request.getParameter("id"));
		if(id==-1){
			Message message = new Message();
			message.setMsg("必须传入角色ID才能编辑!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		String roleName=request.getParameter("roleName")==null?"":request.getParameter("roleName");
		String roleDesc=request.getParameter("roleDesc")==null?"":request.getParameter("roleDesc");
		if("".equals(roleName)||roleName.getBytes().length>=20){
			Message message = new Message();
			message.setMsg("角色名称不能为空且长度必须在20个字节内!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if(roleDesc.getBytes().length>=500){
			Message message = new Message();
			message.setMsg("角色描述长度不能超过500个字节!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		Role role = new Role();
		role.setId((int) id);
		role.setRoleDesc(roleDesc);
		role.setRoleName(roleName);
		User user = (User) request.getSession().getAttribute("user");
		role.setUserId(user.getId());
		role.setUserName(user.getUserName());
		Message message = new Message();
		if(roleService.updateRole(role)<1){
			message.setMsg("网络忙，请稍后再试!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}else{
			message.setMsg("编辑角色成功!");
			message.setStatus("SUCCESS");
			message.setTimestamp(new Date());
			ActionUtil.insertLog(request, MsgType.TYPE_ROLE, "编辑角色:"+roleName,userLogService);
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
		
	}
	@RequestMapping(params = "method=deleteRoleById")
	public String deleteRoleById(HttpServletRequest request,
			HttpServletResponse response, ModelMap map){
		long id = Long.parseLong(request.getParameter("id")==null?"-1":request.getParameter("id"));
		if(id==-1){
			Message message = new Message();
			message.setMsg("必须传入角色ID才能删除!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		Message message = new Message();
		if(roleService.deleteRoleById(id)<1){
			message.setMsg("网络忙，请稍后再试!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}else{
			message.setMsg("删除角色成功!");
			message.setStatus("SUCCESS");
			message.setTimestamp(new Date());
			ActionUtil.insertLog(request, MsgType.TYPE_ROLE, "删除角色:角色ID为"+id,userLogService);
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
		
	}
	@RequestMapping(params = "method=deleteUsersFormRoleById")
	public String deleteUsersFormRoleById(HttpServletRequest request,
			HttpServletResponse response, ModelMap map){
		long id = Long.parseLong(request.getParameter("id")==null?"-1":request.getParameter("id"));
		String userids = request.getParameter("userids");
		if(id==-1){
			Message message = new Message();
			message.setMsg("必须传入角色ID才能删除!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		Message message = new Message();
		if(roleService.deleteUserRoleByRoleId(id,userids)<1){
			message.setMsg("网络忙，请稍后再试!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}else{
			message.setMsg("从角色中删除用户成功!");
			message.setStatus("SUCCESS");
			message.setTimestamp(new Date());
			ActionUtil.insertLog(request, MsgType.TYPE_ROLE, "从角色中删除用户:删除的用户ID为"+userids,userLogService);
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
		
	}
	@RequestMapping(params = "method=addRole")
	public String addRole(HttpServletRequest request,
			HttpServletResponse response, ModelMap map){
		log.info("-----"+request.getParameter("roleName"));
		String roleName=request.getParameter("roleName")==null?"":request.getParameter("roleName");
		String roleDesc=request.getParameter("roleDesc")==null?"":request.getParameter("roleDesc");
		if("".equals(roleName)||roleName.getBytes().length>=20){
			Message message = new Message();
			message.setMsg("角色名称不能为空且长度必须在20个字节内!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if(roleDesc.getBytes().length>=500){
			Message message = new Message();
			message.setMsg("角色描述长度不能超过500个字节!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		Role role = new Role();
		role.setCreateDate(new Date());
		role.setRoleDesc(roleDesc);
		role.setRoleName(roleName);
		User user = (User) request.getSession().getAttribute("user");
		role.setUserId(user.getId());
		role.setUserName(user.getUserName());
		Message message = new Message();
		if(roleService.addRole(role)<1){
			message.setMsg("网络忙，请稍后再试!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}else{
			message.setMsg("新增角色成功!");
			message.setStatus("SUCCESS");
			message.setTimestamp(new Date());
			ActionUtil.insertLog(request, MsgType.TYPE_ROLE, "新增角色:"+roleName,userLogService);
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
		
	}
	@RequestMapping(params = "method=addUserToRole")
	public String addUserToRole(HttpServletRequest request,
			HttpServletResponse response, ModelMap map){
		long id = Long.parseLong(request.getParameter("id")==null?"-1":request.getParameter("id"));
		Message message = new Message();
		if(id==-1){
			message.setMsg("必须传入角色ID才能添加用户!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		String userids=request.getParameter("userids");
		User user = (User) request.getSession().getAttribute("user");
		if(roleService.addUsersToRole(id, userids, user)<0){
			message.setMsg("网络忙，请稍后再试!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}else{
			message.setMsg("添加用户到角色操作成功!");
			message.setStatus("SUCCESS");
			message.setTimestamp(new Date());
			ActionUtil.insertLog(request, MsgType.TYPE_ROLE, "添加用户到角色:用户ID为"+userids,userLogService);
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
		
	}
	@RequestMapping(params = "method=addActionsToRole")
	public String addActionsToRole(HttpServletRequest request,
			HttpServletResponse response, ModelMap map){
		long id = Long.parseLong(request.getParameter("id")==null?"-1":request.getParameter("id"));
		Message message = new Message();
		if(id==-1){
			message.setMsg("必须传入角色ID才能添加操作权限!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		String actionids=request.getParameter("actionids");
		User user = (User) request.getSession().getAttribute("user");
		if(roleService.addActionsToRole(id, actionids, user)<0){
			message.setMsg("网络忙，请稍后再试!");
			message.setStatus("ERROR");
			message.setTimestamp(new Date());
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}else{
			message.setMsg("添加操作权限到角色成功!");
			message.setStatus("SUCCESS");
			message.setTimestamp(new Date());
			ActionUtil.insertLog(request, MsgType.TYPE_ACTION, "设置权限:角色ID为"+id,userLogService);
			try {
				response.getWriter().print(message.toJSONString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
		
	}
}
